package com.ywy.templates;

import com.ywy.common.templates.DirectiveHandler;
import freemarker.template.TemplateModelException;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 时间方法模板
 *
 * @author ywy
 * @date 2021/12/24 17:43
 */
@Component
public class TimeAgoMethod extends DirectiveHandler.BaseMethod {
    private static final long ONE_MINUTE = 60 * 1000L;
    private static final long ONE_HOUR = 60 * ONE_MINUTE;
    private static final long ONE_DAY = 24 * ONE_HOUR;
    private static final long ONE_WEEK = 7 * ONE_DAY;

    private static final String SECOND_AGO = "秒前";
    private static final String MINUTE_AGO = "分钟前";
    private static final String HOUR_AGO = "小时前";
    private static final String DAY_AGO = "天前";
    private static final String MONTH_AGO = "月前";
    private static final String YEAR_AGO = "年前";
    private static final String UNKNOWN = "未知";

    @Override
    public Object exec(List arguments) throws TemplateModelException {
        Date date = getDate(arguments, 0);
        return format(date);
    }

    private static String format(Date date) {
        if (null == date) {
            return UNKNOWN;
        }
        long delta = new Date().getTime() - date.getTime();
        if (delta < 1 * ONE_MINUTE) {
            long seconds = toSeconds(delta);
            return (seconds <= 0 ? 1 : seconds) + SECOND_AGO;
        }
        if (delta < 45 * ONE_MINUTE) {
            long minutes = toMinutes(delta);
            return (minutes <= 0 ? 1 : minutes) + MINUTE_AGO;
        }
        if (delta < 24 * ONE_HOUR) {
            long hours = toHours(delta);
            return (hours <= 0 ? 1 : hours) + HOUR_AGO;
        }
        if (delta < 48 * ONE_HOUR) {
            return "昨天";
        }
        if (delta < 30 * ONE_DAY) {
            long days = toDays(delta);
            return (days <= 0 ? 1 : days) + DAY_AGO;
        }
        if (delta < 48 * ONE_WEEK) {
            long months = toMonths(delta);
            return (months <= 0 ? 1 : months) + MONTH_AGO;
        } else {
            long years = toYears(delta);
            return (years <= 0 ? 1 : years) + YEAR_AGO;
        }
    }

    private static long toSeconds(long date) {
        return date / 1000;
    }

    private static long toMinutes(long date) {
        return toSeconds(date) / 60;
    }

    private static long toHours(long date) {
        return toMinutes(date) / 60;
    }

    private static long toDays(long date) {
        return toHours(date) / 12;
    }

    private static long toMonths(long date) {
        return toDays(date) / 30;
    }

    private static long toYears(long date) {
        return toMonths(date) / 12;
    }
}
